<?php

/**
 * ReferFriends form.
 *
 * @package    docplus.co.za
 * @subpackage form
 * @author     Fox Matuku
 * @version    SVN: $Id: sfDoctrineFormTemplate.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class ReferFriendsForm extends sfForm
{
    protected $cardinals = array('1st', '2nd', '3rd', '4th', '5th');

    public function configure()
    {
        if (!$friends = $this->getOption('friends'))
        {
            throw new InvalidArgumentException('You must provide number of friends you would thank to refer to DocPlus.');
        }

        $this->embedForm(0, new ReferralForm());

        // loop through creating multiple friends on the popup
        for ($i = 1; $i <= $friends; $i++)
        {
            $cardinal = $this->cardinals[$i];
            $form = new ReferralFriendForm(array(), array('cardinal' => $cardinal));
            $this->embedForm($i, $form);
        }

        $this->widgetSchema->setNameFormat('referral[%s]');
    }

	/**
	 * Override the save method to save the merged user form.
	 */
	public function save($con = null) {
		$this->updateUser();
		return parent::save($con);
	}

	/**
	 * Updates the user merged form
	 */
	protected function updateUser() {
		if (!is_null($user = $this->getUser())) {
			if (!$user->getId()) {
				$user->setAlgorithm('md5');
				$user->setEmail($this->getValue("email"));
				$user->setPassword($this->getValue("password"));
			}
			$user->setFirstName($this->getValue("first_name"));
			$user->setLastName($this->getValue("last_name"));
			$user->setEmail($this->getValue("email"));
			$user->setType("Doctor");
			$user->save();

			unset($this->values['first_name'], $this->values['last_name'], $this->values['email'], $this->values['password']);

			// set the user id
			$this->values['user_id'] = $user->get('id');
		}
	}

}
